﻿// // ******************************************************************
// //       /\ /|       @file       StringHelper.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2024-11-10 15:11
// //    *(__\_\        @Copyright  Copyright (c) , 2024-11-10 09:11 Await
// // ******************************************************************

using System.Text.Json;

namespace AutomaticSubtitles.Service.Infrastructure.Helper;

public static class StringHelper
{
    /// <summary>
    /// json转换为对象
    /// </summary>
    /// <param name="data"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T? Deserialize<T>(this string data)
    {
        return JsonSerializer.Deserialize<T>(data);
    }

    /// <summary>
    /// 对象转换为json
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public static string SerializeObject(this object data)
    {
        return JsonSerializer.Serialize(data);
    }

    /// <summary>
    /// 判断结尾是否包含/
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static string AutoPaseUrl(this string url)
    {
        //判断开头http或者https
        if (!url.StartsWith("http://") && !url.StartsWith("https://")) url = "http://" + url;
        //判断结尾是否/
        if (!url.EndsWith("/")) url += "/";
        return url;
    }


    /// <summary>
    ///     从指定数据源中查找具有指定特性的属性，并返回该属性的特性对象。
    /// </summary>
    /// <param name="factoryType"></param>
    /// <typeparam name="TFactoryType"></typeparam>
    /// <typeparam name="TAttribute"></typeparam>
    /// <returns></returns>
    public static TAttribute? FindByAttribute<TFactoryType, TAttribute>(this TFactoryType factoryType)
        where TFactoryType : Enum where TAttribute : Attribute
    {
        var type = typeof(TFactoryType);
        var enumValues = (TFactoryType[])Enum.GetValues(type);
        return (from value in enumValues
            where EqualityComparer<TFactoryType>.Default.Equals(value, factoryType)
            select type.GetField(value.ToString())
            into field
            where Attribute.IsDefined(field, typeof(TAttribute))
            select (TAttribute)Attribute.GetCustomAttribute(field, typeof(TAttribute))).FirstOrDefault();
    }
    
}